﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KMT_Pro.ViewModels;
using System.Windows.Threading;
using KMT_Pro.Utils;
using KMT_Pro.Web;
using System.ServiceModel.DomainServices.Client;

namespace KMT_Pro
{
    public partial class MainPage : UserControl
    {
        LoginViewModel viewModel = new LoginViewModel();
        DispatcherTimer myDispatcherTimer = new DispatcherTimer();

        CustomerContext _context;    

        public MainPage()
        {
            InitializeComponent();

            this.DataContext = viewModel;

            if (Application.Current.InstallState != InstallState.Installed)
            {
                InstallationInstructionControl ctrl = new InstallationInstructionControl();
                LayoutRoot.Children.Add(ctrl);
            }
            else if (!Application.Current.IsRunningOutOfBrowser)
            {
                this.Visibility = System.Windows.Visibility.Collapsed;
                MessageBox.Show("바탕화면에 추가되어 있는 단축 아이콘으로 실행해주세요.");
            }
            else
            {
                Application.Current.MainWindow.WindowState = WindowState.Maximized;
                MenuClear();
                myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 100 Milliseconds 
                myDispatcherTimer.Tick += new EventHandler(Each_Tick);
            }
        }

        public void Each_Tick(object o, EventArgs sender)
        {
            try
            {
                if (!String.IsNullOrEmpty(ClientEnv.GetInstance().CurrentUser.Position))
                {
                    var vm = this.DataContext as LoginViewModel;
                    if (vm == null) return;

                    _context = new CustomerContext();
                    vm.ServerRun(_context.Load(_context.GetUserMenuSelectQuery(ClientEnv.GetInstance().CurrentUser.Position))
                    , (sender1, e) =>
                        {
                            //비동기 이벤트 등록
                            try
                            {
                                LoadOperation lo = sender1 as LoadOperation;
                                foreach (SP_UserMenuSelect_Result GAP in lo.AllEntities)
                                {
                                    MenuVisibility(GAP.MenuName.Trim(), GAP.MenuVisible.Trim());
                                }
                            }
                            catch (Exception)
                            { }
                        });

                    myDispatcherTimer.Stop();
                }
            }
            catch (Exception)
            { }
        }
 

        // 프레임에서 탐색한 후 현재 페이지를 나타내는 HyperlinkButton이 선택되었는지 확인합니다.
        private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            //foreach (UIElement child in LinksStackPanel.Children)
            //{
            //    HyperlinkButton hb = child as HyperlinkButton;
            //    if (hb != null && hb.NavigateUri != null)
            //    {
            //        if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
            //        {
            //            VisualStateManager.GoToState(hb, "ActiveLink", true);
            //        }
            //        else
            //        {
            //            VisualStateManager.GoToState(hb, "InactiveLink", true);
            //        }
            //    }
            //}
        }

        // 탐색하는 동안 오류가 발생하면 오류 창을 표시합니다.
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            e.Handled = true;
            ChildWindow errorWin = new ErrorWindow(e.Uri);
            errorWin.Show();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            viewModel.LayoutRoot = System.Windows.Visibility.Visible;
            MenuClear();
            ContentFrame.Navigate(new Uri("/Home", UriKind.Relative));
        }


        /// <summary>
        /// 메뉴관리용
        /// </summary>
        /// <param name="name"></param>
        /// <param name="TF"></param>
        public void MenuVisibility(string name, string TF)
        {
            switch (name)
            {//-----------------대메뉴---------------------//
                case "관리자메뉴":
                    if (TF == "T")
                        관리자메뉴.Visibility = System.Windows.Visibility.Visible;
                    else
                        관리자메뉴.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                //-----------------대메뉴---------------------//
                case "업체관리":
                    if (TF == "T")
                        업체관리.Visibility = System.Windows.Visibility.Visible;
                    else
                        업체관리.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                //--->>> 
                            case "업체정보관리":
                                if (TF == "T")
                                    업체정보관리.Visibility = System.Windows.Visibility.Visible;
                                else
                                    업체정보관리.Visibility = System.Windows.Visibility.Collapsed;
                                break;

                            case "담당자연락처관리":
                                if (TF == "T")
                                    담당자연락처관리.Visibility = System.Windows.Visibility.Visible;
                                else
                                    담당자연락처관리.Visibility = System.Windows.Visibility.Collapsed;
                                break;
                //<<<---
                //-----------------대메뉴---------------------//
                case "하드웨어관리":
                    if (TF == "T")
                        하드웨어관리.Visibility = System.Windows.Visibility.Visible;
                    else
                        하드웨어관리.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                //--->>> 소메뉴
                        case "장비정보관리":
                    if (TF == "T")
                                장비정보관리.Visibility = System.Windows.Visibility.Visible;
                            else
                                장비정보관리.Visibility = System.Windows.Visibility.Collapsed;
                            break;
                //<<<---
            }
        }

        public void MenuClear()
        {
            관리자메뉴.Visibility = System.Windows.Visibility.Collapsed;
            업체관리.Visibility = System.Windows.Visibility.Collapsed;
            하드웨어관리.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            myDispatcherTimer.Start();
        }
    }
}